package 类加载与字节码技术.类加载器.自定义类加载器;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class MyClassLoadertest1 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        MyClassLoader1 classLoader = new MyClassLoader1("D:\\IdeaProjects\\JVM\\src\\");
        Class<?> c1 = classLoader.loadClass("helloworld");
        Class<?> c2 = classLoader.loadClass("helloworld");
        System.out.println(c1 == c2);

        MyClassLoader1 classLoader2 = new MyClassLoader1("D:\\IdeaProjects\\JVM\\src\\");
        Class<?> c3 = classLoader2.loadClass("helloworld");
        System.out.println(c1 == c3);

        Object o = c1.newInstance();
    }
}

class MyClassLoader1 extends ClassLoader {
    private String bytecodepath;

    public MyClassLoader1(String bytecodepath) {
        this.bytecodepath = bytecodepath;
    }
    @Override // classname 就是类名称
    protected Class<?> findClass(String classname) throws ClassNotFoundException {


        try {

            String path = bytecodepath + classname + ".class";
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Files.copy(Paths.get(path), os);
            //Paths.get(path)：将要复制其数据的文件的路径
            //os：将在其中写入复制数据的输出流

            // 得到字节数组
            byte[] bytes = os.toByteArray();

            // byte[] -> *.class
            return defineClass(null, bytes, 0, bytes.length);

        } catch (IOException e) {
            e.printStackTrace();
            throw new ClassNotFoundException("类文件未找到", e);
        }
    }
}
